package aynu.hd.Hotel.Controller;

import aynu.hd.Config.AlipayConfig;
import aynu.hd.Hotel.Service.orderService;
import aynu.hd.pojo.Orders;
import aynu.hd.pojo.Schedule;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("order")
public class orderController {
    @Autowired
    orderService orderService;

    //付款生成订单
    @PostMapping("addOrder")
    @ResponseBody
    public String addOrder(Orders orders, String num, String room_id, String schedule_id, HttpSession session) {
        String data = orderService.addOrder(orders, num, room_id, schedule_id, session);
        return data;
    }

    //阿里支付沙箱不稳定
    @GetMapping("pay")
    public String payFunction(HttpSession session,Orders orders, HttpServletRequest request) throws IOException, AlipayApiException {
        Orders orders1 = (Orders) session.getAttribute("orders");
        if(orders.getOrders_id()==null){
            orders = orders1;
        }
        orderService.paySuccess(orders.getOrders_id().toString(),request.getSession());
        return "redirect:/order/orderList1";
    }

    //ali支付
    /*@GetMapping("pay")
    public void pay(HttpSession session,Orders orders, HttpServletResponse response) throws IOException, AlipayApiException {
        Orders orders1 = (Orders) session.getAttribute("orders");
        if(orders.getOrders_id()==null){
            orders = orders1;
        }
        System.out.println("支付开始--id-"+orders.getOrders_id()+"------金额---"+orders.getOrders_money());
        // * 开始使用沙箱支付
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        Integer out_trade_no = orders.getOrders_id();
        //付款金额，必填
        Double total_amount = orders.getOrders_money();
        //订单名称，必填
        Integer subject = orders.getOrders_id();
        //商品描述，可空
        String body = "";
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        response.setContentType("text/html");
        response.getWriter().println(result);
    }*/

    //支付成功跳转
    @RequestMapping("/paySuccess")
    public String paySuccess(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");//乱码解决，这段代码在出现乱码时使用
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        if(signVerified) {
            //商户订单号
            String order_id = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //一二无所谓
            //支付宝交易号  1
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //付款金额  2
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
            //支付成功操作
            System.out.println("支付结束--id-"+order_id);
            orderService.paySuccess(order_id,request.getSession());
            return "redirect:/order/orderList1";
        }else {
            return "hotel/orders/error";
        }
    }

    //未付款订单信息
    @RequestMapping("orderList")
    public String orderList(Model model, HttpSession session){
        //查询schedules是为了吧房间的信息带出来
        List<Schedule> schedules = orderService.queryOrderByUser(session);
        model.addAttribute("schedules",schedules);
        return "hotel/orders/order_list";
    }

    //已付款订单信息
    @RequestMapping("orderList1")
    public String orderList1(Model model, HttpSession session){
        //查询schedules是为了吧房间的信息带出来
        List<Schedule> schedules = orderService.queryOrderByUser1(session);
        model.addAttribute("schedules",schedules);
        return "hotel/orders/order_list1";
    }
}
